﻿using System;
using System.Linq;
using System.Web.Mvc;
using WeBlog.Interfaces;
using WeBlog.Models;
using WeBlog.Repositories;

namespace WeBlog.Controllers {
	public class CategoryController : ApplicationController
	{
		private readonly CategoryRepository _repository;      

		public CategoryController(IUnitOfWork unitOfWork)
			: base( unitOfWork )
		{
			_repository = new CategoryRepository(unitOfWork);
		}

        [WeBlogAuthorize(Role.Admin, Role.Editor), Theme("Admin")]
		public ActionResult Manage(GridSettings settings)
		{
			var model = new ManageCategoriesViewModel(settings, UnitOfWork);
			UpdateModel(model);
			return View(model);
		}

		public ActionResult Details(GridSettings settings, string name)
		{
			var model = new CategoryDetailsViewModel(settings, UnitOfWork, name);
			return View(model);
		}
		
		[HttpPost, WeBlogAuthorize(Role.Admin, Role.Editor), Theme("Admin")]
		public JsonResult Create(string name, string description)
		{
			try
			{
				var category = new Category();                
				category.Name = name;
				category.Description = description;
				_repository.Add(category);
				UnitOfWork.Commit();               
				return Json(new JsonResponse { Success = true, Result = category });
			}
			catch (Exception ex)
			{
				return Json(new JsonResponse { Success = false, Message = ex.Message });
			}            
		}

		[HttpPost, WeBlogAuthorize(Role.Admin, Role.Editor), Theme("Admin")]
		public JsonResult Edit(int id, string name, string description)
		{
			JsonResponse result;
			try
			{
				Category category = _repository.FindById(id);                
				category.Name = name;
				category.Description = description;
				UnitOfWork.Commit();     
				result = new JsonResponse { 
							Success = true, 
							Result = new Category { CategoryId = category.CategoryId, Name = category.Name, Description = category.Description } 
				};
			}
			catch (Exception ex)
			{
				result = new JsonResponse { Success = false, Message = ex.Message };
			}

			return Json(result);
		}

		[HttpPost, WeBlogAuthorize(Role.Admin, Role.Editor)]
		public JsonResult Delete(int id)
		{
			try
			{
				var category = _repository.FindById(id); 
				_repository.Remove(category);
				UnitOfWork.Commit();     
				return Json(new JsonResponse { Success = true });
			}
			catch (Exception ex)
			{
				return Json(new JsonResponse { Success = false, Message = ex.Message });
			}
		}
	}
}
